package com.cjb.service.impl;

import com.cjb.entity.Menu;
import com.cjb.mapper.MenuMapper;
import com.cjb.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjb.utils.JsonUtils;
import com.cjb.utils.MenuTreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author kuangjian
 * @since 2022-08-30
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    /**
     * 在这个方法中封装一个需要使用的菜单树json
     * @return
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<Menu> findMenuTree() {
        List<Menu> menus=new ArrayList<>();
        String key="menuList";
        //获取redis的操作对象
        ValueOperations operations = redisTemplate.opsForValue();
        if(!redisTemplate.hasKey(key)){
            //从数据库查询所有菜单
             menus = this.baseMapper.selectList(null);
             String s= JsonUtils.objectToJson(menus);
            //并且往redis中存一份
            operations.set(key,s);
        }else {
            Object o=operations.get(key);
            menus=JsonUtils.jsonToList(o.toString(),Menu.class);
        }
        //是用来构建菜单集合的
        List<Menu> menuList = MenuTreeBuilder.build(menus);
        return menuList;
    }

    @Override
    public List<Long> findOpenIds() {
        List<Long> ids=new ArrayList<>();
        List<Menu> menus = this.baseMapper.selectList(null);
        if(!CollectionUtils.isEmpty(menus)){
            for (Menu menu : menus) {
                if(menu.getOpen()==1){
                    ids.add(menu.getId());
                }
            }
        }
        return ids;
    }

}
